<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>游戏中的物理学-控制移动的小球</title>
<script type="text/javascript" src="../lufylegend-1.7.1.min.js"></script>
</head>
<body>
<div id="mylegend"></div>
<script type="text/javascript">
	init(50,"mylegend",600,400,main);
	var backLayer;
	var ball;
	var KEY = {LEFT:37,RIGHT:39,UP:38,DOWN:40};
	var DIRECTION = {RIGHT:"right",LEFT:"left",UP:"up",DOWN:"down"};
	var STEP = 2;
	function main(){
		//LGlobal.setDebug(true);
		backLayer = new LSprite();
		backLayer.graphics.drawRect(1,"black",[0,0,LGlobal.width,LGlobal.height],true,"black");
		addChild(backLayer);
		addBall();

		//添加键盘事件
		LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_DOWN,onkeydown);
		LEvent.addEventListener(LGlobal.window,LKeyboardEvent.KEY_UP,onkeyup);
	}
	function addBall(){
		ball = new Ball();
		ball.x = 100;
		ball.y = 100;
		backLayer.addChild(ball);
	}
	function onkeydown(e){
		if(ball.direction)return;
		switch(e.keyCode){
			case KEY.LEFT:
				ball.direction = DIRECTION.LEFT;
				break;
			case KEY.RIGHT:
				ball.direction = DIRECTION.RIGHT;
				break;
			case KEY.UP:
				ball.direction = DIRECTION.UP;
				break;
			case KEY.DOWN:
				ball.direction = DIRECTION.DOWN;
				break;
		}
	}
	function onkeyup(e){
		ball.direction = null;
	}
	function Ball(){
		var self = this;
		base(self,LSprite,[]);
		self.r = 10;
		self.graphics.drawArc(1,"gray",[0,0,self.r,0,2*Math.PI],true,"gray");
		self.graphics.drawArc(1,"white",[5,-3,2,0,2*Math.PI],true,"white");
		self.direction = null;
		self.addEventListener(LEvent.ENTER_FRAME,self.onframe);
	}
	Ball.prototype.onframe = function (self){
		switch(self.direction){
			case DIRECTION.LEFT:
				self.x -= STEP;
				break;
			case DIRECTION.RIGHT:
				self.x += STEP;
				break;
			case DIRECTION.UP:
				self.y -= STEP;
				break;
			case DIRECTION.DOWN:
				self.y += STEP;
				break;
		}
	}
</script>
</body>
</html>
